package com.smvc.handlers;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {

	@RequestMapping("upload")
	public String upload(@RequestParam("name") String name, @RequestParam("photo") MultipartFile photo,
			HttpServletRequest request) throws FileNotFoundException, IOException {
		System.out.println("name:" + name + ",fileName:" + photo.getOriginalFilename());
		String realPath = request.getServletContext().getRealPath("/files") + "/" + photo.getOriginalFilename();
		System.out.println(realPath);
		FileCopyUtils.copy(photo.getInputStream(), new FileOutputStream(realPath));
		return "ok";
	}

	@RequestMapping("download")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {

		InputStream is = request.getServletContext().getResourceAsStream("/files/错误.txt");
		byte[] body = new byte[is.available()];
		is.read(body);

		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attachment;filename="+URLEncoder.encode("错误.txt", "utf-8"));

		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
		return response;
	}
}
